/**
 * Configuration Worker - A dedicated thread for sequential file I/O using dxEventBus.
 *
 * This worker subscribes to configuration-related events and handles them
 * one at a time, preventing race conditions.
 */
import std from './dxStd.js';
import dxEventBus from './dxEventBus.js';

/**
 * Handles the save action.
 * @param {object} data - The event data.
 * @param {string} data.path - The file path to save to.
 * @param {object} data.content - The JSON object to save.
 */
function handleSave(data) {
    if (data && data.path && data.content) {
        try {
            // Save with formatting (2-space indent) for better human readability.
            std.saveFile(data.path, JSON.stringify(data.content, null, 2));
        } catch (err) {
            std.err.puts(`[configurationWorker] Error saving file '${data.path}': ${err.message || err}\n`);
        }
    }
}

/**
 * Handles the clear action.
 * @param {object} data - The event data.
 * @param {string} data.path - The file path to delete.
 */
function handleClear(data) {
    if (data && data.path && std.exist(data.path)) {
        try {
            std.remove(data.path);
        } catch (err) {
            std.err.puts(`[configurationWorker] Error clearing file '${data.path}': ${err.message || err}\n`);
        }
    }
}

// Subscribe to the events that the main module will fire.
// The event names are prefixed with '__' as a convention for internal/system events.
dxEventBus.on('__config_save', handleSave);
dxEventBus.on('__config_clear', handleClear);